package 狂神多线程;
//死锁解决方法
public class DeadLock2 {
    public static void main(String[] args) {
        MakeUp2 g1 = new MakeUp2(0, "灰姑凉");
        MakeUp2 g2 = new MakeUp2(1, "白雪公主");
        g1.start();
        g2.start();
    }
}



class Lipstick2{

}



class Mirror2{

}



class MakeUp2 extends Thread{
    //需要的资源只有一份,用static来保证只有一份
    static Lipstick2 lipstick=new Lipstick2();
    static Mirror2 mirror=new Mirror2();
    int choice; //选择
    String girlName;

    public MakeUp2(int choice, String girlName) {
        this.choice = choice;  //选择
        this.girlName = girlName; //使用化妆品的人
    }


    @Override
    public void run() {
        //化妆
        makeup2();
    }

    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup2() {
        if (choice == 0) {
            // 灰姑凉：先拿口红锁，且不释放，同时等待镜子锁
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得口红的锁，等待镜子...");
                try {
                    Thread.sleep(1000); // 故意等待，让另一个线程有机会拿到镜子锁
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 嵌套同步块：持有口红锁的同时，尝试获取镜子锁

            }
            //嵌套同步放在外面
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁，开始化妆");
            }
        } else {
            // 白雪公主：先拿镜子锁，且不释放，同时等待口红锁
            synchronized (mirror) {
                System.out.println(this.girlName + "获得镜子的锁，等待口红...");
                try {
                    Thread.sleep(1000); // 故意等待，让另一个线程有机会拿到口红锁
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 嵌套同步块：持有镜子锁的同时，尝试获取口红锁

            }

            //嵌套同步放在外面即可解决
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得口红的锁，开始化妆");
            }
        }
    }

}